<template>
    <el-dialog v-model="visible" width="500px">
        <h2 class="dialog-title">续费护理项目</h2>
        <el-form :model="form" label-width="120px" class="form-container">
            <el-form-item label="客户姓名：">
                <el-input v-model="form.clientName" disabled />
            </el-form-item>
            <el-form-item label="项目名称：">
                <el-input v-model="form.projectName" disabled />
            </el-form-item>
            <el-form-item label="价格：">
                <el-input v-model="form.price" disabled />
            </el-form-item>
            <el-form-item label="原有数量：">
                <el-input v-model="form.oldQuantity" disabled />
            </el-form-item>
            <el-form-item label="新增数量：" required>
                <el-input-number v-model="form.addQuantity" :min="1" @change="updateEndDateAndTotal"
                    controls-position="right" />
            </el-form-item>
            <el-form-item label="总数量：">
                <el-input :value="totalQuantity" disabled />
            </el-form-item>
            <el-form-item label="续费时长（月）：">
                <el-select v-model="form.renewMonths" placeholder="请选择" @change="updateEndDateAndTotal">
                    <el-option v-for="n in 6" :key="n" :label="`${n} 个月`" :value="n" />
                </el-select>
            </el-form-item>
            <el-form-item label="服务到期日：">
                <el-input :value="calculatedEndDate" disabled />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed, defineExpose, defineEmits } from 'vue'
import { inject } from 'vue'
const axios = inject("axios")
import qs from 'qs'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['renew-success'])

const visible = ref(false)
const form = ref({
    cLId: null,
    clientName: '',
    projectId: '',
    projectName: '',
    price: '',
    oldQuantity: 0,
    addQuantity: 1,
    endDate: '',
    renewMonths: 3 // 默认续费3个月
})

const totalQuantity = computed(() => form.value.oldQuantity + form.value.addQuantity)

const calculatedEndDate = computed(() => {
    const now = new Date()
    now.setMonth(now.getMonth() + form.value.renewMonths)
    return formatDate(now)
})


const updateEndDateAndTotal = () => {
    // 可扩展联动逻辑
}

const handleSubmit = async () => {
    if (!form.value.addQuantity || form.value.addQuantity <= 0) {
        ElMessage.warning('请填写有效的新增数量')
        return
    }

    try {
        const params = {
            cLId: form.value.cLId,
            quantity: totalQuantity.value,
            endDate: calculatedEndDate.value
        }
        const res = await axios.post(
            '/clientNursingProject/updateClientNursingProject',
            qs.stringify(params),
            { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
        )
        if (res.data.status === 200) {
            ElMessage.success('续费成功')
            visible.value = false
            emit('renew-success')
        } else {
            throw new Error(res.data.msg)
        }
    } catch (err) {
        ElMessage.error('续费失败：' + err.message)
    }
}

const formatDate = (date) => {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
}

const open = (data) => {
    form.value = {
        cLId: data.clientNursingProject.cLId,
        clientName: data.client.name,
        projectId: data.nursingProject.projectId,
        projectName: data.nursingProject.name,
        price: data.nursingProject.price,
        oldQuantity: data.clientNursingProject.quantity,
        addQuantity: 1,
        endDate: data.clientNursingProject.endDate,
        renewMonths: 3
    }
    updateEndDateAndTotal() // 🟢 强制刷新 endDate 计算
    visible.value = true
}


defineExpose({ open })
</script>
<style scoped>
.dialog-title {
    font-size: 27.2px;
    font-weight: bold;
    margin: 0 0 20px 0;
    color: #333;
}

.form-container {
    padding: 10px 0;
}

.el-input,
.el-input-number {
    width: 100%;
}

.el-select {
    width: 100%;
}
</style>
